package com.qiangesoft.datasourcembpd.service.impl;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.datasourcembpd.entity.BcgDataSource;
import com.qiangesoft.datasourcembpd.mapper.BcgDataSourceMapper;
import com.qiangesoft.datasourcembpd.service.IBcgDataSourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;

/**
 * <p>
 * 数据源 服务实现类
 * </p>
 *
 * @author qiangesoft
 * @since 2024-03-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BcgBcgDataSourceServiceImpl extends ServiceImpl<BcgDataSourceMapper, BcgDataSource> implements IBcgDataSourceService {

    private final DataSource dataSource;

    private final DynamicDataSourceProperties properties;

    private final DataSourceCreator druidDataSourceCreator;

    @Override
    public List<BcgDataSource> changeDataSource(String datasourceId) {
        BcgDataSource bcgDataSource = baseMapper.selectById(Long.valueOf(datasourceId));

        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setPoolName(bcgDataSource.getId().toString());
        dataSourceProperty.setDriverClassName(bcgDataSource.getDriverClassName());
        dataSourceProperty.setUrl(bcgDataSource.getUrl());
        dataSourceProperty.setUsername(bcgDataSource.getUsername());
        dataSourceProperty.setPassword(bcgDataSource.getPassword());
        dataSourceProperty.setDruid(properties.getDruid());

        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty);
        ds.addDataSource(dataSourceProperty.getPoolName(), dataSource);

        return this.list();
    }

    @DS("slave")
    @Override
    public List<BcgDataSource> changeDataSourceByAnnotation() {
        return this.list();
    }
}
